class Semaphor::Reports::TopUserAgent < Semaphor::Reports::Base
  
  self.category = "Programmer"
  self.title = "Top 10 Browsers"
  self.template = :rank
  self.cols = [
    ['count', "Hits"],
    ['percent', "%"],
    ['browser', "Browser"]
  ]
  
  def run
  	query = %{
      SELECT COUNT(*) AS count,
              user_agent
      FROM hits
      GROUP BY user_agent
      ORDER BY count DESC
    }

    raw_data = db.select_all(query)
    counts = Hash.new 0
    
    total = db.select_value("SELECT COUNT(*) FROM hits").to_f
    
    raw_data.each do |row|
      case row['user_agent']
      	when /(Firefox)\/(.*)/
          counts["#{$~[1]} #{$~[2]}"] += row['count'].to_i
        when /MSIE\s(.*?);/
          counts["Internet Explorer #{$~[1]}"] += row['count'].to_i
        when /(Safari)\/(.*)/
          counts["#{$~[1]} #{$~[2]}"] += row['count'].to_i
        else
          counts[row['user_agent']] += row['count'].to_i
      end
    end
    
    @data = counts.collect{|k,v| {'count' => v, 'browser' => k, 'percent' => v / total * 100.0}}
    @data.sort!{|a,b| b['count'] <=> a['count']}
    @data = @data[0..9]
    
  end
    
end
